<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2 modal_main">
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="queryParams.fileName" placeholder="请输入模型名" clearable />
          </el-form-item>
          <el-form-item label="上传日期">
            <el-date-picker style="width: 240px" v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
          </el-form-item>
          <el-form-item style="padding-left: 80px">
            <el-button size="small" type="primary" icon="search" @click="handleQuery">查询</el-button>
            <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Plus"
              @click="handleAdd">新增模型</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="文件名" align="left" prop="fileName" width="180" fixed="left" />
        <el-table-column label="网格格式" align="left" prop="meshFormat" />
        <el-table-column label="支持的求解器" align="left" prop="solver" />
        <el-table-column label="业务场景" align="left" prop="businessName" />
        <el-table-column label="来源方式" align="left" prop="importMethod" />
        <el-table-column label="备注" align="left" prop="remarks" />
        <el-table-column label="创建人" align="left" prop="createByName" />
        <el-table-column label="创建时间" align="left" prop="createTime" />
        <el-table-column label="操作" align="left" width="250" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button size="small" link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button size="small" link type="primary" icon="Edit" @click="download(scope.row)">下载</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:remove']" link type="primary" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <pagination v-show="total > 0" style="margin-top: 0;" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" :total="total" :background="false"
          layout="total, sizes, prev, pager, next, jumper" @pagination="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="visible" :title="currentData?.id ? '修改模型' : '新增模型'" width="780px" append-to-body @close="cancel">
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="160px" size="small">
        <el-form-item label="支持的求解器" prop="solver">
          <el-input placeholder="请输入支持的求解器	" v-model="form.solver" />
        </el-form-item>
        <el-form-item label="业务场景" prop="businessName">
          <el-input placeholder="请输入业务场景	" v-model="form.businessName" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input placeholder="请输入备注	" v-model="form.remarks" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file" v-if="!currentData?.id">
          <el-upload :before-upload="handleBeforeUpload" @change="handleChange" :on-remove="handleRemove"
            :file-list="fileList" :show-file-list="true" :auto-upload="false" :multiple="false" :limit="1" action="#">
            <el-button size="small" type="primary">选取文件</el-button>
            <div class="el-upload__tip">模型文件大小超过1GB,请走离线方式</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Oss">
import { getAcousticModelList, addAcousticModel, updateAcousticModel, deleteAcousticModel, downloadFile } from '@/api/acousticsIsotropic/index.js';
const loading = ref(false);
const uploadVisible = ref(false);
const ossFormRef = ref(null);
const dateRange = ref([]);
const initFormData = {
  solver: '',
  businessName: '',
  remarks: '',
};
const form = ref({ ...initFormData });
const queryParams = ref({
  // 查询参数
  pageNum: 1,
  pageSize: 10,
  fileName: '',
});
const fileList = ref([]);
const rules = ref({
  solver: [{ required: true, message: '求解器不能为空', trigger: 'blur' }],
  businessName: [{ required: true, message: '业务场景不能为空', trigger: 'blur' }],
});
const tableData = ref([]);
const total = ref(0);
const visible = ref(false);
const currentData = ref(null);
const getList = async () => {
  loading.value = true;
  try {
    console.log(queryParams.value)
    queryParams.value.beginCreateTime = dateRange.value && dateRange.value.length > 0 ? dateRange.value[0] : '';
    queryParams.value.endCreateTime = dateRange.value && dateRange.value.length > 0 ? dateRange.value[1] : '';
    const response = await getAcousticModelList(queryParams.value);
    tableData.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};
const handleRemove = (event) => {
  const index = fileList.value.indexOf(event);
  if (index > -1) {
    fileList.value.splice(index, 1);
  }
};
const handleChange = (event) => {
  fileList.value.push(event);
};
const handleBeforeUpload = (file) => {
  // const isDat = file.name.endsWith('.dat');
  // if (!isDat) {
  //   ElMessage.error('只能上传.dat格式的文件!');
  // }
  // return isDat;
};
const resetQuery = () => {
  queryParams.value.fileName = '';
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  dateRange.value = [];
  getList();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
const handleAdd = () => {
  visible.value = true;
};
const handleUpload = () => {
  // 批量上传逻辑
  uploadVisible.value = true;
};
const handleDelete = (row) => {
  ElMessageBox.confirm('是否确认删除该模型？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteAcousticModel(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!',
    });
    getList();
  }).catch(() => {
    // 取消删除
  });
};
const handleEdit = (row) => {
  Object.assign(form.value, row);
  currentData.value = row;
  visible.value = true;
};
const handleCurrentChange = (newPage) => {
  // queryParams.value.pageNum = newPage;
  getList();
};
const submitForm = () => {
  ossFormRef.value.validate(async (valid) => {
    if (valid) {
      if (currentData.value?.id) {
        await updateAcousticModel(form.value);
        ElMessage({
          type: 'success',
          message: '修改成功!',
        });
      } else {
        const formData = new FormData();
        if (fileList.value.length === 0) {
          ElMessage.error('请上传模型文件!');
          return;
        }
        formData.append('file', fileList.value[0].raw);
        formData.append('solver', form.value.solver);
        formData.append('businessName', form.value.businessName);
        formData.append('remarks', form.value.remarks);
        form.value.id = null;
        await addAcousticModel(formData);
        ElMessage({
          type: 'success',
          message: '新增成功!',
        });
      }
      visible.value = false;
      Object.assign(form.value, initFormData);
      currentData.value = null;
      fileList.value = [];
      getList();
    }
  });
};
const cancel = () => {
  visible.value = false;
  currentData.value = null;
  Object.assign(form.value, initFormData);
};
const download = (row) => {
  downloadFile(row.id).then((response) => {
    const blob = new Blob([response], { type: 'application/octet-stream' });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = row.fileName+row.meshFormat;
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
};
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.modal_main {
  height: calc(100vh - 180px);
  overflow: auto;
}

.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}

:deep(.el-upload) {
  display: block;
}
</style>